package org.jeecg.modules.tea_stu_course.controller;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.entity.SysUserTit;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.course.entity.AstuCourse;
import org.jeecg.modules.course.service.IAstuCourseService;
import org.jeecg.modules.student.entity.AstuInformation;
import org.jeecg.modules.student.service.IAstuInformationService;
import org.jeecg.modules.tea_stu_course.entity.AstuTeastuCourse;
import org.jeecg.modules.tea_stu_course.service.IAstuTeastuCourseService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.teacher.entity.AstuTeacher;
import org.jeecg.modules.teacher.service.IAstuTeacherService;

import org.jeecg.modules.vo.AstuTeacherCourseDTO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 老师学生课程交汇表
 * @Author: jeecg-boot
 * @Date:   2021-10-12
 * @Version: V1.0
 */
@Api(tags="老师学生课程交汇表")
@RestController
@RequestMapping("/tea_stu_course/astuTeastuCourse")
@Slf4j
public class AstuTeastuCourseController extends JeecgController<AstuTeastuCourse, IAstuTeastuCourseService> {
	@Autowired
	private IAstuTeastuCourseService astuTeastuCourseService;
	@Autowired
	private IAstuTeacherService astuTeacherService;
	@Autowired
	private IAstuInformationService astuInformationService;
	@Autowired
	private IAstuCourseService astuCourseService;
	/**
	 * 分页列表查询
	 *
	 * @param astuTeastuCourse
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//老师只能看到选了自己课的学生的选课表信息
	@AutoLog(value = "老师学生课程交汇表-分页列表查询")
	@ApiOperation(value="老师学生课程交汇表-分页列表查询", notes="老师学生课程交汇表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AstuTeastuCourse astuTeastuCourse,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Subject subject = SecurityUtils.getSubject();
		LoginUser user = (LoginUser)subject.getPrincipal();
		List<AstuTeastuCourse> list = null;
		Page<AstuTeacherCourseDTO> page1 = new Page(pageNo, pageSize);
		List<AstuTeacherCourseDTO> list1=new ArrayList<>();
		if (user.getUsername().equals("admin")){
			list = astuTeastuCourseService.list();
		}else {
			list = astuTeastuCourseService.list(new QueryWrapper<AstuTeastuCourse>().eq("student_number", user.getUsername()));
		}
		//BeanUtils.copyProperties(page,page1,"records");
		for (AstuTeastuCourse item : list) {
			AstuTeacherCourseDTO astuTeacherCourseDTO = new AstuTeacherCourseDTO();
			BeanUtils.copyProperties(item,astuTeacherCourseDTO);
			//老师工号
			String teacherNumber = item.getTeacherNumber();
			//学生学号
			String studentNumber = item.getStudentNumber();
			//课程号
			String courseId = item.getCourseId();
			//获取老师姓名
			LambdaQueryWrapper<AstuTeacher> QueryWrapper = new LambdaQueryWrapper<>();
			QueryWrapper.eq(AstuTeacher::getTeacherNumber,teacherNumber);
			AstuTeacher one = astuTeacherService.getOne(QueryWrapper);
			//设置教师姓名
			String teacherName = one.getTeacherName();
			astuTeacherCourseDTO.setTeacherName(teacherName);
			//获取学生姓名
			LambdaQueryWrapper<AstuInformation> studentQueryWrapper = new LambdaQueryWrapper<>();
			studentQueryWrapper.eq(AstuInformation::getStuNumber,studentNumber);
			AstuInformation one1 = astuInformationService.getOne(studentQueryWrapper);
			String stuName = one1.getStuName();
			//设置学生姓名
			astuTeacherCourseDTO.setStudentName(stuName);
			//获取课程名称
			LambdaQueryWrapper<AstuCourse> qw = new LambdaQueryWrapper<>();
			qw.eq(AstuCourse::getCourseNumber,courseId);
			AstuCourse course = astuCourseService.getOne(qw);
			String courseName= course.getCourseName();
			//设置课程名称
			astuTeacherCourseDTO.setCourseName(courseName);
			list1.add(astuTeacherCourseDTO);
		}
		list1.sort((t1, t2) -> t2.getCreateTime().compareTo(t1.getCreateTime()));
		page1.setRecords(list1);
		return Result.OK(page1);
	}

	/**
	 * 添加
	 *
	 * @param astuTeastuCourse
	 * @return
	 */
	@AutoLog(value = "老师学生课程交汇表-添加")
	@ApiOperation(value = "老师学生课程交汇表-添加", notes = "老师学生课程交汇表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AstuTeacherCourseDTO astuTeastuCourse) {
		//若教师表中没有新增教师，返回错误
		AstuTeacher teacher= null;
		try {
			String teacherNumber = astuTeastuCourse.getTeacherNumber();
			teacher = astuTeastuCourseService.selectByTeaNum(teacherNumber);
		} catch (NullPointerException e) {
			return Result.error("教师工号有误,添加失败");
		}
		if (teacher == null){
			return Result.error("教师表中没有该教师信息,添加失败");
		}
		//若学生表中没有学生信息，返回错误
		AstuInformation student= null;
		String studentNumber = astuTeastuCourse.getStudentNumber();
		try {
			student = astuTeastuCourseService.selectByStuNum(studentNumber);
		} catch (NullPointerException e) {
			return Result.error("学号有误,添加失败");
		}
		if (student == null){
			return Result.error("学生表中没有学生信息,添加失败");
		}
		//若课程表中没有课程信息，返回错误
		AstuCourse course= null;
		String courseId = astuTeastuCourse.getCourseId();
		try {
			course = astuTeastuCourseService.selectByCourseNum(courseId);
		} catch (NullPointerException e) {
			return Result.error("课程号有误,添加失败");
		}
		if (course == null){
			return Result.error("课程表中没有课程信息,添加失败");
		}
		//教师，学生，课程都存在
		//判断是否已经选过客
		AstuTeastuCourse teastuCourse = astuTeastuCourseService.selectinfoByStuNumAndCourseNum(studentNumber, courseId);
		if (teastuCourse!=null){
			return Result.error("该学生已选该课程,添加失败");
		}
		AstuTeastuCourse astuTeastuCourse1 = new AstuTeastuCourse();
		BeanUtils.copyProperties(astuTeastuCourse,astuTeastuCourse1);
		astuTeastuCourseService.save(astuTeastuCourse1);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param astuTeastuCourseDTO
	 * @return
	 */
	@AutoLog(value = "老师学生课程交汇表-编辑")
	@ApiOperation(value = "老师学生课程交汇表-编辑", notes = "老师学生课程交汇表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody AstuTeacherCourseDTO astuTeastuCourseDTO) {
		//判断学生
		String studentName = null;
		String stuName = null;
		try {
			studentName = astuTeastuCourseDTO.getStudentName();
			String studentNumber = astuTeastuCourseDTO.getStudentNumber();
			AstuInformation student = astuTeastuCourseService.selectByStuNum(studentNumber);
			stuName = student.getStuName();
		} catch (NullPointerException e) {
			return Result.error("学号错误,编辑失败");
		}
		if (!stuName.equals(studentName)) {
			return Result.error("学生学号与姓名不符,编辑失败");
		}

		//判断老师
		String teacherName = null;
		String teacherName1 = null;
		try {
			String teacherNumber = astuTeastuCourseDTO.getTeacherNumber();
			AstuTeacher teacher=astuTeastuCourseService.selectByTeaNum(teacherNumber);
			teacherName = teacher.getTeacherName();
			teacherName1 = astuTeastuCourseDTO.getTeacherName();
		} catch (NullPointerException e) {
			return Result.error("学号错误,编辑失败");
		}
		if (!teacherName.equals(teacherName1) || StringUtils.isBlank(teacherName1)){
			return  Result.error("教师工号与姓名不符,添加失败");
		}

		//判断课程
		String courseName = null;
		String courseName1 = null;
		try {
			String courseId = astuTeastuCourseDTO.getCourseId();
			AstuCourse course=astuTeastuCourseService.selectByCourseNum(courseId);
			courseName = astuTeastuCourseDTO.getCourseName();
			courseName1 = course.getCourseName();
		} catch (NullPointerException e) {
			return Result.error("学号错误,编辑失败");
		}
		if (!courseName1.equals(courseName)|| StringUtils.isBlank(courseName1)){
			return Result.error("课程编号与课程名称不相符,添加失败");
		}
		AstuTeastuCourse astuTeastuCourse = new AstuTeastuCourse();
		BeanUtils.copyProperties(astuTeastuCourseDTO, astuTeastuCourse);
		astuTeastuCourseService.updateById(astuTeastuCourse);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "老师学生课程交汇表-通过id删除")
	@ApiOperation(value="老师学生课程交汇表-通过id删除", notes="老师学生课程交汇表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		astuTeastuCourseService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "老师学生课程交汇表-批量删除")
	@ApiOperation(value="老师学生课程交汇表-批量删除", notes="老师学生课程交汇表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch( String ids) {
		this.astuTeastuCourseService.removeByIds(Arrays.asList(ids.split(",")));
		log.info("批量删除===========>学生选课信息");
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "老师学生课程交汇表-通过id查询")
	@ApiOperation(value="老师学生课程交汇表-通过id查询", notes="老师学生课程交汇表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AstuTeastuCourse astuTeastuCourse = astuTeastuCourseService.getById(id);
		if(astuTeastuCourse==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(astuTeastuCourse);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param astuTeastuCourse
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AstuTeacherCourseDTO astuTeastuCourse) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<AstuTeastuCourse> List = astuTeastuCourseService.list();
		ArrayList<AstuTeacherCourseDTO> listdto = new ArrayList<>();
		for (AstuTeastuCourse item : List) {
			AstuTeacherCourseDTO astuTeacherCourseDTO = new AstuTeacherCourseDTO();
			BeanUtils.copyProperties(item, astuTeacherCourseDTO);
			String courseId = item.getCourseId();
			AstuCourse course = astuTeastuCourseService.selectByCourseNum(courseId);
			String courseName = course.getCourseName();
			astuTeacherCourseDTO.setCourseName(courseName);

			String studentNumber = item.getStudentNumber();
			AstuInformation astuInformation = astuTeastuCourseService.selectByStuNum(studentNumber);
			String stuName = astuInformation.getStuName();
			astuTeacherCourseDTO.setStudentName(stuName);

			String teacherNumber = item.getTeacherNumber();
			AstuTeacher astuTeacher = astuTeastuCourseService.selectByTeaNum(teacherNumber);
			String teacherName = astuTeacher.getTeacherName();
			astuTeacherCourseDTO.setTeacherName(teacherName);
			listdto.add(astuTeacherCourseDTO);
		}
		log.info("listdto === > {}" ,listdto );
		//导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "学生选课表");
		//注解对象Class
		mv.addObject(NormalExcelConstants.CLASS, AstuTeacherCourseDTO.class);
		//自定义导出字段 		   mv.addObject(NormalExcelConstants.EXPORT_FIELDS,"name,keyWord,punchTime");
		//自定义表格参数
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("学生选课表报表", "导出人:" + sysUser.getRealname(),"学生选课表"));
		//导出数据列表
		mv.addObject(NormalExcelConstants.DATA_LIST, listdto);
		return mv;
	}
    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		// 将request变成多部分request
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			//标题
			params.setTitleRows(2);
			//表头
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				//List  导入的数据
				List<AstuTeacherCourseDTO> list = ExcelImportUtil.importExcel(file.getInputStream(), AstuTeacherCourseDTO.class, params);
				long start = System.currentTimeMillis();
				SysUserTit user = null;
				for (AstuTeacherCourseDTO astuTeastuCourse : list) {
					//学生的学号
					String studentNumber = astuTeastuCourse.getStudentNumber();
					//老师的工号
					String teacherNumber = astuTeastuCourse.getTeacherNumber();
					//课程号
					String courseId = astuTeastuCourse.getCourseId();
					//如果没有，跳到下一条
					if (studentNumber==null ||teacherNumber==null||courseId==null ){
						continue;
					}
					//设置学生姓名
					AstuInformation astuInformation = astuInformationService.selectByStuNum(studentNumber);
					String stuName = astuInformation.getStuName();
					astuTeastuCourse.setStudentName(stuName);
					//设置老师姓名
					AstuTeacher astuTeacher = astuTeacherService.selectInfoByTeacherNum(teacherNumber);
					String teacherName = astuTeacher.getTeacherName();
					astuTeastuCourse.setTeacherName(teacherName);
					//设置课程名
					AstuCourse astuCourse = astuCourseService.selectInfoByCourseNum(courseId);
					String courseName = astuCourse.getCourseName();
					astuTeastuCourse.setCourseName(courseName);
					//查询学生选课数据
					AstuTeastuCourse course = astuTeastuCourseService.selectAstuTeastuCourseByStudentNumberAndteacherNumberAndCourseId(studentNumber, teacherNumber, courseId);
					//判断用户是否存在，当用户存在时，便可以导入
					if (astuInformation !=null){
						//过滤重复的数据
						if (course==null){
							AstuTeastuCourse astuTeastuCourse1 = new AstuTeastuCourse();
							BeanUtils.copyProperties(astuTeastuCourse,astuTeastuCourse1);
							astuTeastuCourseService.save(astuTeastuCourse1);
						}
					}
				}
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功!");
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}
}
